package com.niit.session21;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

import com.niit.session20.JDBCUtils;

public class UserDao {
//	1.把数据导入mysql，打开工作台，打开链接，创建查询，把student_2021.sql拖进去执行
//	2.把驱动包放到项目中：右键项目名字创建lib文件夹，把mysql-connector-java-8.0.27.jar拖到lib中--》右键build path -->add to build path
//	3.把JDBCUtils拖到项目中
	
	public static void main(String[] args) {
		UserDao userDao = new UserDao();
		try {
			Scanner sc = new Scanner(System.in);
			userDao.login(sc.nextLine(), sc.nextLine());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void login(String username,String password) throws SQLException {
		Connection conn = JDBCUtils.getConn();
//		如果使用字符串拼接的SQL语句，会导致SQL注入
//		Statement statement = conn.createStatement();
//		String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";
//		通过prepareStatement获得一个PrepareStatement对象，参数全部改成问好? ,?代表占位符
//		prepareStatement会无害化处理字符串拼接过程中的分号;，可以避免SQL注入的发生
		PreparedStatement ps = conn.prepareStatement("select * from user where username = ? and password = ?");
//		给问好占位符填参数，下标从1开始，指的是第几个问好，第二个参数是要填入的值
		ps.setString(1, username);
		ps.setString(2, password);
		
		System.out.println(ps.toString());
		ResultSet rs = ps.executeQuery();
		if(rs.next()) {
			System.out.println("登录成功！");
		}else {
			System.out.println("登录失败");
		}
	}

}
